import { ref } from 'vue'
import MessageBox from './notify.vue';
import { mountComponent, useNotifyState } from './utils';

/**
 * 蒋这些代码提取出来，传一个组件进来动态生成
 * @type {{loading: string}}
 */
const defaultMessage = {
  loading: '正在拼了全站流量给您加载...'
};

function filterOptions (options) {
  let option = {
    duration: 1500
  };
  switch (typeof options) {
    case 'string':
    case 'number':
      option.message = options;
      break;
    case 'object':
      option = options;
      break;
  }
  return option;
}
// let iRef = null
const Message = options => {
  const { instance: notifyInstance, unmount } = mountComponent({
    setup () {
      const root = ref('')
      const { state, close } = useNotifyState();
      function onMessageBoxClose () {
        close()
        unmount()
      }
      // onMounted(() => {
      // iRef = root.value
      // 这里能拿到 MessageBox 组件实例（有属性，有方法）
      // console.log(root.value)
      // })
      return () => (
        <MessageBox
          ref={root}
          { ...Object.assign({ 'onUpdate:show': onMessageBoxClose }, options, state) }
        />
      )
    }
  })
  // setTimeout(() => {
  //   // 通过这个手段就能拿到实例的方法
  //   iRef.onClose()
  // }, 2000)
  notifyInstance.open()
  Message.close = function () {
    notifyInstance.close()
    unmount()
  };
  return notifyInstance;
};

['success', 'warning', 'info', 'error'].forEach(type => {
  Message[type] = options => {
    options = filterOptions(options);
    options.type = type;
    return Message(options);
  };
});

Message.loading = function (options) {
  const defaultOptions = {
    type: 'loading',
    message: '',
    duration: 0
  };
  const optionType = typeof options;
  if (['string', 'number'].includes(optionType)) {
    defaultOptions.message = options;
  } else if (optionType === 'object') {
    defaultOptions.message = options.message || defaultMessage['loading'];
  } else {
    defaultOptions.message = defaultMessage['loading'];
  }
  Object.assign(defaultOptions, filterOptions(options));
  if (!defaultOptions.message) {
    defaultOptions.message = defaultMessage['loading'];
  }
  return Message(defaultOptions);
};

export default Message;
